import Sound from 'react-native-sound';

// 在静音模式下启用播放
Sound.setCategory('Playback');

let sound: Sound;

const init = (filepath: string) => {
  return new Promise((resolve, reject) => {
    sound = new Sound(filepath, '', error => {
      if (error) {
        console.log('failed to load the sound', error);
        reject(error);
      } else {
        resolve(sound);
      }
    });
  });
};
// 播放知道播放完成结束才会返回
const play = () => {
  return new Promise((resolve, reject) => {
    if (sound) {
      sound.play(success => {
        //success是个boolean值   代表播放是否成功
        if (success) {
          console.log('successfully finished playing');
          resolve(sound);
        } else {
          console.log('playback failed due to audio decoding errors');
          reject();
        }
        //释放资源
        // sound.release();
      });
    } else {
      reject();
    }
  });
};
// 暂停
const pause = () => {
  return new Promise(resolve => {
    if (sound) {
      sound.pause(() => {
        resolve(1);
      });
    } else {
      resolve(1);
    }
  });
};
// 停止
const stop = () => {
  return new Promise(resolve => {
    if (sound) {
      sound.stop(() => {
        resolve(1);
      });
    } else {
      resolve(1);
    }
  });
};
//获取当前播放时间
const getCurrentTime = () => {
  return new Promise(resolve => {
    if (sound && sound.isLoaded()) {
      sound.getCurrentTime(resolve);
    } else {
      resolve(0);
    }
  });
};

//获取音频市场
const getDuration = () => {
  if (sound) {
    return sound.getDuration();
  }
  return 0;
};

export {sound, init, play, pause, getCurrentTime, stop, getDuration};
